<template>
  <el-dialog
    title="新增文章"
    :visible.sync="visible"
    width="60%"
    append-to-body
  >
    <avue-form
      v-if="visible"
      ref="addForm"
      v-model="form"
      :option="tableOption"
      :upload-exceed="uploadExceed"
      :upload-error="uploadError"
      :upload-change="$uploadChange"
      :upload-before="uploadBefore"
    >
    </avue-form>
    <div
      v-if="!actionFlag"
      class="flex-end"
    >
      <el-button @click="visible = false">取消</el-button>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="confirm(ARTICLE_STATUS.DRAFT)"
      >
        保存
      </el-button>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click="confirm(ARTICLE_STATUS.PUBLISHED)"
      >
        发布
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex';
import { addObj, getObj, editObj } from '@/api/core/articleManage';
import { tableOption } from '@/const/crud/content/add-article';
import { ARTICLE_STATUS } from '@/const/type';
import { BROADCAST_TYPE } from '@/const/type';
import { getOfficialList } from '@/api/app/customer';
export default {
  name: 'Detail',
  props: {
    id: {
      type: [Object, String],
    },
    value: {
      type: Boolean,
      default: false,
    },
    action: { type: [String] },
  },
  data() {
    return {
      form: {},
      loading: false,
      ARTICLE_STATUS,
      width: '',
      height: '',
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
    ...mapGetters(['userInfo', 'access_token']),
    actionFlag() {
      return this.action === 'view';
    },
    tableOption() {
      return tableOption(this.actionFlag);
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          this.form.fileType = BROADCAST_TYPE.PICTURE;
          this.id && this.getDetail();
        });
      } else {
        this.$refs.addForm && this.$refs.addForm.resetForm();
      }
    },
    'form.userPhone': {
      immediate: true,
      async handler(val) {
        if (val) {
          const res = await getOfficialList({ param: val });
          const obj = res.data.data.find((el) => el.phone === val);
          this.form.userId = obj.userId;
          this.form.userName = obj.nickname;
          this.form.userAvatar = obj.avatar;
        } else {
          this.form.userId = '';
          this.form.userName = '';
          this.form.userAvatar = '';
        }
      },
    },
  },
  methods: {
    async getDetail() {
      const res = await getObj(this.id);
      if (res.data.data) {
        this.form = { ...res.data.data };
        this.form.label = JSON.parse(this.form.label);
        const temp = JSON.parse(this.form.files).map((el) => el.url);
        if (this.form.fileType === BROADCAST_TYPE.PICTURE) {
          this.form.petPicture = temp;
        } else {
          this.form.petVideo = temp;
        }
      }
    },
    confirm(status) {
      this.$refs.addForm.validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          try {
            const params = { ...this.form, status };
            params.label = JSON.stringify(this.form.label);
            const temp = [];
            if (params.fileType === BROADCAST_TYPE.PICTURE) {
              params.petPicture.forEach((el) => {
                temp.push({ fileName: '', url: el, width: 0.75, height: 1 });
              });
              params.poster = params.petPicture[0]; // 图片取第一张
            } else {
              temp.push({
                fileName: '',
                url: params.petVideo,
                width: this.width,
                height: this.height,
              });
              params.poster = `${params.petVideo}?vframe/jpg/offset/0`; // 视频取第一帧
            }
            if (this.id) {
              params.id = this.id;
            }
            params.files = JSON.stringify(temp);
            const callback = this.id ? editObj : addObj;
            await callback(params);
            this.$message.success('操作成功');
            this.$emit('success', true);
            done();
            this.loading = false;
            this.visible = false;
          } catch (error) {
            done();
            this.loading = false;
            throw new Error(error);
          }
        }
      });
    },
    async uploadBefore(file, done, loading, column) {
      const flag = await this.getMp4Time(file);
      if (!flag) {
        loading();
        this.$message.warning('上传视频时长在三分钟以内！');
        return false;
      }
      // this.transcode(file);
      done();
    },
    getMp4Time(file) {
      return new Promise((resolve) => {
        const fileExtend = file.name
          .substring(file.name.lastIndexOf('.'))
          .toLowerCase();
        //如果是mp4
        if (
          fileExtend === '.mp4' ||
          fileExtend === '.mpeg' ||
          fileExtend === '.WMV' ||
          fileExtend === '.mov'
        ) {
          //把element上传组件传给我们的file转成url
          const url = URL.createObjectURL(file);
          //获取mp4对象
          const v = document.createElement('video');
          v.src = url;
          //监听事件
          v.addEventListener('loadedmetadata', () => {
            //时间
            const time = Math.ceil(v.duration * 100) / 100;
            console.log('time', time, v.videoWidth, v.videoHeight);
            this.width = v.videoWidth;
            this.height = v.videoHeight;
            if (time > 4 * 60) {
              console.log('进来了码');
              resolve(false);
            } else {
              resolve(true);
            }
          });
        } else {
          //不是mp4
          resolve(true);
        }
      });
    },
    //文件大小
    uploadError(error, column) {
      if (error === '文件太大不符合') {
        this.$message.warning(`文件大小不能超过${column.fileSize / 1024}M`);
      }
    },
    uploadExceed(limit, files, fileList, column) {
      console.log(limit, files, fileList, column);
      this.$message.error(`只能上传${limit}个文件`);
    },
  },
};
</script>

<style lang='scss' scoped>
</style>
